package com.jiuhao.service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.jiuhao.api.BaiduApiService;
import com.jiuhao.dto.DocumentInfoDto;
import com.jiuhao.dto.SegmentsDto;
import com.jiuhao.entity.KnowledgeDocument;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import retrofit2.Response;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class BaiduService {


    private final BaiduApiService baiduApiService;
    private final ElasticsearchService elasticsearchService;

    public DocumentInfoDto getDocumentDetail(String documentId) {
        try {
            Response<DocumentInfoDto> response = baiduApiService.getDocumentDetail(
                    documentId, 1, 1).execute();
            if (response.isSuccessful()) {
                return response.body();
            } else {
                // 处理错误响应
                System.err.println("Error: " + response.code() + " " + response.message());
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public SegmentsDto getDocumentSegments(String documentId) {
        try {
            long timestamp = System.currentTimeMillis();
            Response<SegmentsDto> response = baiduApiService.getDocumentSegments(
                    documentId, "", "", timestamp, 1, 1).execute();
            if (response.isSuccessful()) {
                return response.body();
            } else {
                System.err.println("Error: " + response.code() + " " + response.message());
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Map<String, Object> getDocEs(String documentId) {
        DocumentInfoDto documentDetail = this.getDocumentDetail(documentId);
        SegmentsDto documentSegments = this.getDocumentSegments(documentId);
        Integer detailCode = documentDetail.getCode();
        Integer segmentCOde = documentSegments.getCode();
        String detailMsg = documentDetail.getMsg();
        String segmentMsg = documentSegments.getMsg();
        DocumentInfoDto.DocumentDesc detailDto = documentDetail.getData();
        SegmentsDto.Data segmentDto = documentSegments.getData();
        if (detailCode == 200 && segmentCOde == 200) {
            String agentId = detailDto.getAgentId();
            int available = detailDto.getAvailable();
            // TODO 待确认
            String label = detailDto.getLabels();
            String dirId = detailDto.getDirId();
            String docId = detailDto.getId();
            String effectStartTime = detailDto.getEffectStartTime();
            // TODO 待确认
            String version = "";
            String effectEndTime = detailDto.getEffectEndTime();
            String documentName = detailDto.getName();
            int knowledgePublic = detailDto.getKnowledgePublic();
            List<String> titleContentJoin = Lists.newArrayList();
            String titleContentStr = StrUtil.EMPTY;
            List<SegmentsDto.Segment> list = segmentDto.getList();
            if (CollUtil.isNotEmpty(list)) {
                list.forEach(v -> {
                    String segmentTitle = v.getSegment_title_list().stream().collect(Collectors.joining(""));
                    String segmentContent = v.getSegment_content();
                    titleContentJoin.add(segmentTitle + segmentContent);
                });
                titleContentStr = titleContentJoin.stream().collect(Collectors.joining(""));
            }
            titleContentStr = documentName + " " + titleContentStr;
            log.info(titleContentStr);

            KnowledgeDocument knowledgeDocument = new KnowledgeDocument().setAgentId(agentId)
                    .setAvailable(Convert.toStr(available))
                    .setLabel(label)
                    .setDirId(dirId)
                    .setDocumentId(docId)
                    .setEffectStartTime(DateUtil.parse(effectStartTime, "yyyy-MM-dd HH:mm:ss"))
                    .setVersion(Convert.toLong(version))
                    .setEffectEndTime(DateUtil.parse(effectEndTime, "yyyy-MM-dd HH:mm:ss"))
                    .setDocumentName(documentName)
                    .setSentenceContent("");
            try {
                String s = elasticsearchService.addDocument(knowledgeDocument);
                log.info("新增文档成功,id:{}", s);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else {
            log.error("获取文档详情失败,msg:{}", detailMsg);
            log.error("获取文档分段失败,msg{}", segmentMsg);
        }
        return null;
    }
}